import 'package:flutter/material.dart';
import 'package:flutter_smart_heating/common/app.dart';
import 'package:flutter_smart_heating/common/event.dart';
import 'package:flutter_smart_heating/common/global.dart';
import 'package:flutter_smart_heating/common/http.dart';
import 'package:flutter_smart_heating/pages/home/widget/home_popup_view.dart';
import 'package:flutter_smart_heating/pages/home/widget/home_weather_view.dart';
import 'package:flutter_smart_heating/ui/src/pull_to_refresh.dart';
import 'package:flutter_smart_heating/ui/ui.dart';
import 'package:get/get.dart';
import 'widget/home_station_info_view.dart';
import 'widget/home_search_view.dart';
import 'widget/home_menu_view.dart';
import 'widget/home_swiper_view.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  RefreshController refreshController = RefreshController();
  List<dynamic> banner = [];
  List<dynamic> menu = [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}];
  ValueNotifier badges = ValueNotifier<int>(0);
  Map<String, dynamic> weather = {};
  int refreshTotal = 0;
  dynamic eventBus;
  @override
  void initState() {
    super.initState();
    getAllData();
    eventBus =
        AppEvent().eventBus.on<RootNavigateChangeEvent>().listen((event) async {
      if (event.name == 'home') {
        await getBadges();
      }
    });
  }

  @override
  void dispose() {
    eventBus.cancel();
    super.dispose();
  }

  getAllData() async {
    refreshTotal++;
    fetchGallery();
    fetchWeather();
    getBadges();
    await 0.5.delay();
    refreshController.refreshCompleted();
    setState(() {});
  }

  getBadges() async {
    await GlobalData.getBadge();
    badges.value = GlobalData.badges['messager'] ?? 0;

    if (GlobalData.badges['popup']?['show'] == true) {
      showDialog(
        context: Get.context!,
        barrierDismissible:
            GlobalData.badges['popup']?['barrierDismissible'] ?? false,
        builder: (context) {
          return Center(
            child: HomePopupView(
              option: HomePopupOption.fromJson(
                  GlobalData.badges['popup']['option']),
              list: GlobalData.badges['popup']['list'],
            ),
          );
        },
      );
    }
  }

  fetchGallery() async {
    var res = await Http.instance.post(
      '/plugin/gallery/api/group',
      data: {"name": 'homeSwiper,homeMenu'},
    );

    setState(() {
      banner = res.data['homeSwiper']['list'].first;
      menu = res.data['homeMenu']['list'].first;
    });
    GlobalData.menu = menu;
  }

  fetchWeather() async {
    var res = await Http.instance.post('/api/information/weather/station');
    setState(() {
      weather = res.data;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: false,
      backgroundColor: UiTheme(context).match(light: Colors.white),
      appBar: AppBar(
        backgroundColor: UiTheme.of(context).match(
          light: UiTheme.primary,
        ),
        foregroundColor: UiTheme(context).match(light: Colors.white),
        title: const HomeSearchView(),
        leading: ValueListenableBuilder(
            valueListenable: badges,
            builder: (context, state, child) {
              return IconButton(
                onPressed: () async {
                  await App.push('/messager');
                  await .3.delay();
                  await getBadges();
                },
                icon: Badge(
                  backgroundColor: Colors.red,
                  isLabelVisible: state > 0,
                  smallSize: 8,
                  child: const Icon(UiIcons.bell),
                ),
              );
            }),
        leadingWidth: 50,
        titleSpacing: 0,
        actions: [
          SizedBox(
            width: 50,
            child: IconButton(
              onPressed: () {
                App.push('/qrcode');
              },
              padding: EdgeInsets.zero,
              icon: const UiIcon(
                UiIcons.saoma,
              ),
            ),
          ),
        ],
      ),
      body: UiPushToRefresh(
        controller: refreshController,
        onRefresh: () {
          getAllData();
        },
        child: ListView(
          padding: EdgeInsets.zero,
          children: [
            Container(
              padding: const EdgeInsets.only(
                top: UiTheme.toolbarSpacing,
                left: UiTheme.spacingX,
                right: UiTheme.spacingX,
              ),
              decoration: UiTheme(context).match(
                light: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [
                      UiTheme.primary,
                      UiTheme(context).match(
                          light: Colors.white,
                          dark: Theme.of(context).scaffoldBackgroundColor),
                    ],
                    stops: const [0.4, 1],
                  ),
                ),
              ),
              child: SafeArea(
                child: Column(
                  children: [
                    HomeSwiperView(items: banner),
                    const UiLineBreak(),
                  ],
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: UiTheme.spacingX),
              child: Column(
                children: [
                  HomeMenuView(items: menu),
                  const UiLineBreak(),
                  // HomeNoticeView(),
                  // const UiLineBreak(),
                  HomeStationInfoView(key: ValueKey('home.$refreshTotal')),
                  const UiLineBreak(),
                  HomeWeatherView(weather: weather),
                  const UiLineBreak(),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
